<template>
	<div class="login-wrap">
		<el-form ref="form" :model="user" :rules="rules">
			<h2>登 录</h2>
			<el-form-item prop="mobile">
				<el-input v-model="user.mobile" placeholder="请输入手机号"></el-input>
			</el-form-item>
			<el-form-item prop="code">
				<el-input v-model="user.code" placeholder="请输入验证码"></el-input>
			</el-form-item>
			<el-form-item prop="agree">
				<el-checkbox v-model="user.agree">我已阅读并同意用户协议和隐私条款</el-checkbox>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="login" :loading="loadingvalue" style="width: 100%;">登录</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	import {login} from '@/api/request/user.js'
	export default {
		data() {
			return {
				user: {
					mobile: '13911111111', 
					code: '246810' ,
					agree:false
				},
				loadingvalue:false,
				rules:{
					mobile: [
						{ required: true, message: '请输入手机号', trigger: 'change' },
						{ pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'change' }
					],
					code: [
						{ required: true, message: '验证码不能为空', trigger: 'change' },
						{ pattern: /^\d{6}$/, message: '请输入正确的验证码格式' }
					],
					agree: [
						{
							// 自定义校验规则：https://element.eleme.cn/#/zh-CN/component/form#zi-ding-yi-xiao-yan-gui-ze
							// 验证通过：callback()
							// 验证失败：callback(new Error('错误消息'))
							validator: (rule, value, callback) => {
								if (value) {
									callback()
								} else {
									callback(new Error('请同意用户协议'))
								}
							},
							// message: '请勾选同意用户协议',
							trigger: 'change'
						}
					]
				}
			}
		},
		methods: {
			login() {
				// 表单验证
				this.$refs['form'].validate(valid=>{
					if(!valid){return}
					this.pass()
				})
			},
			pass(){
				// 验证通过，提交登录
				this.loadingvalue= true
				login(this.user).then(res => {
					// 登录成功
					this.$message({
						message: '登录成功',
						type: 'success'
					})
					// 关闭 loading
					this.loadingvalue = false
					//相关数据存储本地方便共享，只能存字符串
					window.localStorage.setItem('user',JSON.stringify(res.data.data))
					//跳转到首页
					this.$router.push('/')
				}).catch(err => {
					// 登录失败
					this.$message.error('登录失败，手机号或验证码错误')
					// 关闭 loading
					this.loadingvalue = false
				})
			}	
		}
	}
</script>

<style scoped lang="less">
	.login-wrap{
		position: fixed;
		left: 0;
		top:0;
		right: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: pink;
		.el-form{
			padding: 0 30px;
			background-color: rgba(255,255,255,0.5);
			h2{
				text-align: center;
				margin-bottom: 15px;
			}
		}
	}
</style>
